#coding=utf-8

def post_save(sender, instance, created, data, old_data):
    from uliweb.orm import get_model
    import pickle
    from datetime import datetime
    from uliweb import request
    
    if sender.tablename == 'resource':
        HumanHis = get_model('humanhis')
        
        changed_value = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
        if created:
            modify_flag = '1'
            old_value = ''
        else:
            #如果系统和角色发生变化，则记录历史
            if ('system' in data) or ('role' in data) or ('delete_flag' in data):
                if data.get('delete_flag'):
                    modify_flag = '3'
                    old_value = pickle.dumps(instance.to_dict(), pickle.HIGHEST_PROTOCOL)
                    changed_value = ''
                else:
                    modify_flag = '2'
                    old = {}
                    for k in data.iterkeys():
                        old[k] = old_data[k]
                    old_value = pickle.dumps(old, pickle.HIGHEST_PROTOCOL)
            else:
                return
            
        obj = HumanHis(user=instance._user_, changed_value=changed_value,
            old_value=old_value, modified_date=datetime.now(), modified_user=request.user,
            modify_flag=modify_flag)
            
        obj.save()
    
def pre_delete(sender, instance):
    from uliweb.orm import get_model
    import pickle
    from datetime import datetime
    from uliweb import request
    
    if sender.tablename == 'resource':
        HumanHis = get_model('humanhis')
        
        changed_value = ''
        old_value = pickle.dumps(instance.to_dict(), pickle.HIGHEST_PROTOCOL)
        modify_flag = '3'
            
        obj = HumanHis(user=instance._user_, changed_value=changed_value,
            old_value=old_value, modified_date=datetime.now(), modified_user=request.user,
            modify_flag=modify_flag)
            
        obj.save()
    
